<template>
	<picker mode="multiSelector" :range="multiArray" :value="multiIndex" @change="onPickerChange"
		@columnchange="onColumnChange">
		<slot></slot>
	</picker>
</template>
<script>
	import { areaData } from './location.js';
	export default {
		data() {
			return {
				multiArray: [[],[],[]], // 三级数据容器
				multiIndex: [0, 0, 0], // 当前选中索引
				selectedText: '' ,// 显示的选择结果
				addressData:{
					province:'',
					city:'',
					area:'',
					province_adcode:'',
					city_adcode:'',
					area_adcode:'',
				}
			}
		},
		created() {
			this.initPickerData();
		},
		methods: {
			// 初始化选择器数据
			initPickerData() {
				// 第一级：省份
				this.multiArray[0] = areaData.map(item => item.name);

				// 第二级：默认第一个省份的城市
				const firstProvince = areaData[0];
				this.multiArray[1] = firstProvince.children.map(city => city.name);

				// 第三级：默认第一个城市的区域
				const firstCity = firstProvince.children[0];
				this.multiArray[2] = firstCity.children.map(area => area.name);
			},

			// 列数据变化时（滑动某列）
			onColumnChange(e) {
				const {
					column,
					value
				} = e.detail; // 变化的列索引和值索引

				// 更新选中索引
				const newIndex = [...this.multiIndex];
				newIndex[column] = value;

				// 根据列变化更新数据
				if (column === 0) { // 省份变化
					const province = areaData[value];
					// 更新城市列表
					this.multiArray[1] = province.children.map(city => city.name);
					// 更新区域列表（默认取第一个城市）
					this.multiArray[2] = province.children[0].children.map(area => area.name);
					// 重置下级索引
					newIndex[1] = 0;
					newIndex[2] = 0;
				} else if (column === 1) { // 城市变化
					const provinceIndex = this.multiIndex[0];
					const cityIndex = value;
					// 更新区域列表
					this.multiArray[2] = areaData[provinceIndex].children[cityIndex].children.map(area => area.name);
					// 重置下级索引
					newIndex[2] = 0;
				}

				// 更新索引和数据
				this.multiIndex = newIndex;
				this.$forceUpdate(); // 强制刷新视图
			},

			// 确定选择
			onPickerChange(e) {
				const indices = e.detail.value;
				const [provinceIdx, cityIdx, areaIdx] = indices;
				
				// 获取选中文本
				const province = areaData[provinceIdx].name;
				const city = areaData[provinceIdx].children[cityIdx].name;
				const area = areaData[provinceIdx].children[cityIdx].children[areaIdx].name;
				
				// 获取选中的adcode
				const province_adcode = areaData[provinceIdx].adcode;
				const city_adcode = areaData[provinceIdx].children[cityIdx].adcode;
				const area_adcode = areaData[provinceIdx].children[cityIdx].children[areaIdx].adcode;

				// 更新显示文本
				this.selectedText = `${province} - ${city} - ${area}`;
				this.multiIndex = indices; // 更新索引状态

				// 更新数据
				this.addressData = {
					province,
					city,
					area,
					province_adcode,
					city_adcode,
					area_adcode,
				}

				// 触发选择事件
				this.$emit('select', this.addressData,this.selectedText);
			},
		}
	}
</script>
<style>
</style>